﻿using System;
using System.Windows.Forms;
//using CommonStructs;
using WeifenLuo.WinFormsUI.Docking;
//using ObjectModel;
using System.IO;
using TaleGeneratorModel;
using System.Data.EntityClient;
using System.Data.SqlServerCe;
using System.Linq;
//using Generator;


namespace TaleGeneratorInterface
{
	public partial class MainForm : Form
	{
		NetForm FrameNetForm;

		private string currentDatabaseConnectionString;
		private string currentDatabasePath;
		TaleClasses frameNet;
		SqlCeConnection conn;
		//FrameEditorForm Editor;
		//FrameNet frameNet;
		//Controller controller;

		public MainForm()
		{
			InitializeComponent();

			toolStrip1.Enabled = false;

			//Editor = new FrameEditorForm();
			//Editor.FormClosing += new FormClosingEventHandler(Editor_FormClosing);

			редакторФреймаToolStripMenuItem.Checked = false;
			//DockContent frmX1 = Editor;
			//frmX1.ShowHint = DockState.DockBottom;
			//frmX1.Show(dockPanel2); 
			btnDrawFrame.Checked = false;
			btnMove.Checked = false;
			btnDrawIsA.Checked = false;
			редакторДоменовToolStripMenuItem.Enabled = false;
			сохранитьToolStripMenuItem.Enabled = false;
			сохранитьКакToolStripMenuItem.Enabled = false;
			скомпилироватьToolStripMenuItem.Enabled = false;
			cbScale.SelectedIndex = 2;
		}

		void Editor_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (e.CloseReason == CloseReason.UserClosing)
			{
				редакторФреймаToolStripMenuItem.Checked = false;
				(sender as DockContent).Hide();
			}
		}

		private void НовыйФайлToolStripMenuItem_Click(object sender, EventArgs e)
		{
			NewNetForm form = new NewNetForm();
			form.Text = "Создать сеть фреймов";
			cbScale.SelectedIndex = 2;
			if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				if (FrameNetForm != null)
					FrameNetForm.Close();
				сохранитьToolStripMenuItem.Enabled = true;
				сохранитьКакToolStripMenuItem.Enabled = true;
				скомпилироватьToolStripMenuItem.Enabled = true;

				//frameNet = FrameNet.CreateFrameNet(form.KBName,form.KBPath);


				new DbGenerator().CreateDatabase(Path.Combine(form.KBPath, form.KBName + ".sdf"));

				currentDatabaseConnectionString = "DataSource=" + Path.Combine(form.KBPath, form.KBName + ".sdf");
				currentDatabasePath = Path.Combine(form.KBPath, form.KBName + ".sdf");

				conn = new SqlCeConnection("DataSource=" + Path.Combine(form.KBPath, form.KBName + ".sdf"));
				conn.Open();
				frameNet = new TaleClasses(conn);

				//SqlCeConnection conn = new SqlCeConnection("DataSource=" + Path.Combine(form.KBPath, form.KBName + ".sdf"));
				//conn.Open();
				//TaleClasses ct = new TaleClasses(conn);
				//ct.Domain.InsertOnSubmit(new Domain() { Name = "aaa" });
				//ct.SubmitChanges();
				//var dom = from d in ct.Domain
				//        select d;
				//foreach(var d in dom)
				//    MessageBox.Show(d.Name);

				if (!редакторФреймаToolStripMenuItem.Checked)
				{
					редакторФреймаToolStripMenuItem.Checked = true;
					ShowFrameEditor();
				}

				//	Editor.SetFrameNet(frameNet);

				// FrameNetForm = new NetForm();
				// FrameNetForm.FormClosing += new FormClosingEventHandler(FrameNetForm_FormClosing);
				//// controller = new Controller(frameNet, FrameNetForm.VisualBoxNew);
				// AssignControllerEventHandlers();
				// DockContent frmX = FrameNetForm;
				// frmX.ShowHint = DockState.Document;
				// frmX.Text = frameNet.Name;
				// frmX.Show(dockPanel2);



				// редакторДоменовToolStripMenuItem.Enabled = true;

				// toolStrip1.Enabled = true;
				// FrameNetForm.State = ViewState.Modify;
			}
		}

		void FrameNetForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			DialogResult dres = MessageBox.Show("Сохранить базу перед закрытием?", "", MessageBoxButtons.YesNoCancel);
			switch (dres)
			{
				case System.Windows.Forms.DialogResult.Yes:
					//frameNet.Save();
					break;
				case System.Windows.Forms.DialogResult.No:
					break;
				case System.Windows.Forms.DialogResult.Cancel:
					e.Cancel = true;
					break;
			}
		}



		private void AssignControllerEventHandlers()
		{
			//controller.EventAllUnselected += new CommonStructs.EmptyEvent(controller_EventAllUnselected);
			//controller.EventFrameSelected += new CommonStructs.FrameEvent(controller_EventFrameSelected);
			//controller.EventFrameSlotsChanged += new CommonStructs.FrameSlotsEvent(controller_EventFrameSlotsChanged);
			//controller.EventLinkSelected += new CommonStructs.LinkEvent(controller_EventLinkSelected);
		}

		//void controller_EventLinkSelected(CommonStructs.LinkData linkData)
		//{
		//    Editor.ShowFrameSlots(linkData.idFrameFrom);
		//    if (linkData.type == CommonStructs.LinkType.SubFrame)
		//        Editor.SelectSlot(linkData.name);
		//}

		void controller_EventFrameSlotsChanged(int frameId)
		{

		}

		//void controller_EventFrameSelected(CommonStructs.FrameData frameData)
		//{
		//    Editor.ShowFrameSlots(frameData.id);
		//}

		void controller_EventAllUnselected()
		{
			//    Editor.ClearContent();
		}

		private void toolStripButton1_Click(object sender, EventArgs e)
		{
			//    if (btnDrawFrame.Checked)
			//    {
			//        btnMove.Checked = btnDrawSubFrame.Checked = btnDrawIsA.Checked = false;			  
			//        FrameNetForm.State = ViewState.DoNothing;                
			//    }
			//    else
			//        FrameNetForm.State = ViewState.Modify;
		}

		private void btnDrawIsA_Click(object sender, EventArgs e)
		{
			//    if (btnDrawIsA.Checked)
			//    {
			//        btnMove.Checked = btnDrawSubFrame.Checked = btnDrawFrame.Checked = false;
			//        FrameNetForm.linkType = LinkType.IsA;
			//        FrameNetForm.State = ViewState.DrawLinks;
			//    }
			//    else
			//    {
			//        FrameNetForm.State = ViewState.Modify;
			//    }
		}

		private void btnDrawHasA_Click(object sender, EventArgs e)
		{
			//    if (btnDrawSubFrame.Checked)
			//    {
			//        btnMove.Checked = btnDrawIsA.Checked = btnDrawFrame.Checked = false;
			//        FrameNetForm.linkType = LinkType.SubFrame;
			//        FrameNetForm.State = ViewState.DrawLinks;
			//    }
			//    else
			//    {
			//        FrameNetForm.State = ViewState.Modify;
			//    }
		}

		private void btnMove_Click(object sender, EventArgs e)
		{
			//    if (btnMove.Checked)
			//    {
			//        btnDrawSubFrame.Checked = btnDrawIsA.Checked = btnDrawFrame.Checked = false;
			//        FrameNetForm.State = ViewState.Pan;
			//    }
			//    else
			//    {
			//        FrameNetForm.State = ViewState.Modify;
			//    }
		}

		private void toolStripButton1_Click_1(object sender, EventArgs e)
		{
			//    if (FrameNetForm.State == ViewState.DoNothing)
			//        FrameNetForm.VisualBoxNew.DelPress();
			//    //if (FrameNetForm.State == VisualLib.VisualBox.StateOfVisual.Observe)
			//        //FrameNetForm.stateClass.PreviewKeyDown(Keys.Delete);
		}

		private void выходToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//    this.Close();
		}

		private void редакторФреймаToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (редакторФреймаToolStripMenuItem.Checked)
			{
				ShowFrameEditor();
			}
			else
			{
				//(Editor as DockContent).Hide();
			}
		}


		void ShowFrameEditor()
		{
			//    if (Editor == null || Editor.IsDisposed)
			//    {
			//        Editor = new FrameEditorForm(frameNet);
			//        Editor.FormClosing += new FormClosingEventHandler(Editor_FormClosing);
			//    }
			//        редакторФреймаToolStripMenuItem.Checked = true;
			//        DockContent frmX = Editor;
			//        frmX.ShowHint = DockState.DockBottom;
			//        frmX.Show(dockPanel2);

		}


		private void редакторДоменовToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//    DomainEditorForm form = new DomainEditorForm(frameNet);
			//    form.ShowDialog();
		}

		private void сохранитьToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//    if (frameNet != null)
			//    {
			//        frameNet.Save();
			//    }
		}

		private void загрузитьToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//cbScale.SelectedIndex = 2;
			//OpenFileDialog dlg = new OpenFileDialog();
			//dlg.Filter = "Файлы сетей фреймов (*.sdf)|*.sdf";
			//dlg.InitialDirectory = "c:\\temp";
			//if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			//{				
			//    if (FrameNetForm != null)
			//        FrameNetForm.Close();

			//    string path = dlg.FileName;
			//    string name=Path.GetFileNameWithoutExtension(path);
			//    string dir=Path.GetDirectoryName(path);

			//    frameNet = FrameNet.CreateFrameNet(0,name, dir);
			//    сохранитьToolStripMenuItem.Enabled = true;
			//    сохранитьКакToolStripMenuItem.Enabled = true;
			//    скомпилироватьToolStripMenuItem.Enabled = true;

			//    if (!редакторФреймаToolStripMenuItem.Checked)
			//    {
			//        редакторФреймаToolStripMenuItem.Checked = true;
			//        ShowFrameEditor();
			//    }

			//    Editor.SetFrameNet(frameNet);

			//    FrameNetForm = new Form1();
			//    FrameNetForm.FormClosing += new FormClosingEventHandler(FrameNetForm_FormClosing);
			//    controller = new Controller(frameNet, FrameNetForm.VisualBoxNew);
			//    AssignControllerEventHandlers();
			//    DockContent frmX = FrameNetForm;
			//    frmX.ShowHint = DockState.Document;
			//    frmX.Text = frameNet.Name;
			//    frmX.Show(dockPanel2);

			//    frameNet.Load(path);

			//    редакторДоменовToolStripMenuItem.Enabled = true;

			//    toolStrip1.Enabled = true;
			//    btnDrawFrame.Checked = false;
			//    btnMove.Checked = false;
			//    btnDrawIsA.Checked = false;
			//    FrameNetForm.State = ViewState.Modify;
			//}
		}

		private void cbScale_SelectedIndexChanged(object sender, EventArgs e)
		{
			//if (controller != null)
			//{
			//    int zoom = int.Parse(cbScale.SelectedItem.ToString().Substring(0, cbScale.SelectedItem.ToString().Length - 1));
			//    controller.ViewSetZoom(zoom);
			//}
		}

		private void фреймToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//btnDrawFrame.Checked = true;
			//toolStripButton1_Click(null, null);
		}

		private void связьIsAToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//btnDrawIsA.Checked = true;
			//btnDrawIsA_Click(null, null);
		}

		private void cdzpmHasToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//btnMove.Checked = true;
			//btnDrawHasA_Click(null,null);
		}

		private void перемещатьВсёToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//btnMove.Checked = true;
			//btnMove_Click(null, null);
		}

		private void сохранитьКакToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//SaveFileDialog dlg = new SaveFileDialog();
			//dlg.CheckPathExists = true;			
			//dlg.FileName = frameNet.Name + ".sdf";
			//if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			//{
			//    try
			//    {
			//        frameNet.Save(dlg.FileName);
			//        FrameNetForm.Text = Path.GetFileNameWithoutExtension(dlg.FileName);
			//    }
			//    catch
			//    {
			//        MessageBox.Show("Не удалось сохранить базу по указанному пути");
			//    }
			//}
		}

		private void toolStripButton1_Click_2(object sender, EventArgs e)
		{
			//if (toolStripButton1.Checked)
			//{
			//    btnDrawHasA.Checked = btnDrawIsA.Checked = btnDrawFrame.Checked = false;
			//    FrameNetForm.State = ViewState.Pan;
			//}
			//else
			//{
			//    FrameNetForm.State = ViewState.Modify;
			//}
		}

		private void dockPanel2_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
		{
			//FrameNetForm.VisualBoxNew.PreviewKeyPressed(e.KeyData);
		}

		private void MainForm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
		{
			//  FrameNetForm.VisualBoxNew.PreviewKeyPressed(e.KeyData);
		}

		private void справкаToolStripMenuItem_Click(object sender, EventArgs e)
		{
			helpProvider1.SetHelpNavigator(this, HelpNavigator.TableOfContents);
		}

		private void видToolStripMenuItem_Click(object sender, EventArgs e)
		{

		}

		private void скомпилироватьToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//GenerationForm form = new GenerationForm();
			//form.DatabaseName = frameNet.Name;
			//form.AssemblyName = frameNet.Name;
			//if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			//{
			//    switch (MessageBox.Show("Сохранить базу перед компиляцией?", "", MessageBoxButtons.YesNoCancel))
			//    {
			//        case System.Windows.Forms.DialogResult.Yes:
			//            frameNet.Save();
			//            CompileFrameNet(form.ServerName, form.DatabaseName, form.AssemblyName, form.AssemblyPath);
			//            break;
			//        case System.Windows.Forms.DialogResult.No:
			//            CompileFrameNet(form.ServerName, form.DatabaseName, form.AssemblyName, form.AssemblyPath);
			//            break;
			//        case System.Windows.Forms.DialogResult.Cancel:
			//            return;
			//    }
			//}
		}

		private void CompileFrameNet(string serverName, string databaseName, string assemblyName, string assemblyCatalog)
		{
			//FrameNetCompiler.CompileFrameNet(frameNet.FullPath, serverName, databaseName, assemblyName, assemblyCatalog);
		}

	}
}
